package com.huaxindata.im.main.chat.Helper;

import android.app.Activity;
import android.content.Context;
import android.content.res.AssetFileDescriptor;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Vibrator;

import com.huaxindata.im.R;
import com.huaxindata.im.main.manager.ContactManager;
import com.huaxindata.im.main.manager.HistoryContactManager;
import com.huaxindata.im.main.manager.UserManager;
import com.huaxindata.im.model.contact.ContactTmp;
import com.huaxindata.im.model.db.ContactStore;
import com.huaxindata.im.model.db.LocalAnnoStore;
import com.huaxindata.im.model.db.LocalWarnStore;
import com.huaxindata.im.model.db.MessageStore;
import com.huaxindata.im.model.entity.ChatMessage;
import com.huaxindata.im.model.entity.ChatSysMessageBody;
import com.huaxindata.im.model.entity.HxAnnoModel;
import com.huaxindata.im.model.entity.HxWarnModel;
import com.huaxindata.im.util.Log;

import java.io.IOException;

import static android.content.Context.VIBRATOR_SERVICE;

/**
 * Created by Administrator on 2017/9/4.
 * 帮助处理接收到的消息
 */

public class MessageHelper {
    private static MediaPlayer mediaPlayer;
    private static Vibrator    vibrator;

    public static MediaPlayer getMediaPlayer(Context context) {
        if (mediaPlayer != null) {
            return mediaPlayer;
        }
        if (context instanceof Activity)
            ((Activity) context).setVolumeControlStream(AudioManager.STREAM_MUSIC);
        mediaPlayer = new MediaPlayer();
        mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
        /**
         * When the beep has finished playing, rewind to queue up another one.
         */
        mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                mediaPlayer.seekTo(0);
            }
        });
        mediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
            @Override
            public boolean onError(MediaPlayer mp, int what, int extra) {
                mediaPlayer.release();
                mediaPlayer = null;
                return true;
            }
        });
        AssetFileDescriptor file;
        file = context.getResources().openRawResourceFd(R.raw.msg);
        try {
            mediaPlayer.setDataSource(file.getFileDescriptor(),
                    file.getStartOffset(), file.getLength());
            file.close();
            float BEEP_VOLUME = 1.0f;
            mediaPlayer.setVolume(BEEP_VOLUME, BEEP_VOLUME);
            mediaPlayer.prepare();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return mediaPlayer;
    }

    public static Vibrator getVibrator(final Context context) {
        if (vibrator != null) {
            return vibrator;
        }
        vibrator = (Vibrator) context.getSystemService(VIBRATOR_SERVICE);
        return vibrator;
    }

    /**
     * 处理系统消息的具体逻辑的方法
     */
    public static void handleSystemMessage(ChatMessage message) {
        // String content=message.message;
        ChatSysMessageBody messageBody = (ChatSysMessageBody) message.getMessageBody();
        if (messageBody.content == null) {//如果消息的内容主体为空，则不处理
            Log.e("xxx", "xxx=====消息主体为空");
            return;
        }
        // String[] msgBody = content.split(HxMessage.PREX);//消息体内容
        String[] msgBody = messageBody.getSystemMessageInfo();
        String action = messageBody.action;
        Log.e("xxx", "xxx=====处理系统消息：" + action);
        if (ChatSysMessageBody.SysMessageType.ACTION_RESP_FED.equals(action)) {
            if ("2".equals(msgBody[2])) {
                //收到被好友删除的消息、则同时在自己经通讯录中删除好友，历史聊天记录
                ContactManager.removeFriend(message.sender);
                HistoryContactManager.deleteHistory(message.sender);
                MessageStore.deleteFriendMsg(message.sender, UserManager.getClientId());
                Log.e("xxx", "xxx==收到被删除的消息:" + msgBody[2]);
            } else if ("1".equals(msgBody[2])) {
                //如果申请对方添加好友，对方同意之后发过来的确认
                Log.e("xxx", "xxx==对方同意添加你为好友:" + msgBody[2]);
                ContactManager.initData();
            } else if ("0".equals(msgBody[2])) {
                Log.e("xxx", "xxx==对方拒绝添加你为好友:" + msgBody[2]);
            }
        } else if (ChatSysMessageBody.SysMessageType.ACTION_RQST_FED.equals(action)) {
            Log.e("xxx", "xxx==收到请求添加好友消息");
            ContactTmp tmp = new ContactTmp(message.sender, msgBody[1], null);
            ContactStore.insert(tmp, 0, message.timestamp);
        } else if (ChatSysMessageBody.SysMessageType.ACTION_CREATE_GROUP.equals(action)) {
            //收到建群消息，要订阅群消息并刷新群列表
            Log.e("xxx", "xxx==收到建群消息");
            ContactManager.initData();
            if (sCallback != null) {
                sCallback.onMessageHelperCallback(message.sender, true);
            }
        } else if (ChatSysMessageBody.SysMessageType.ACTION_DESTROY_GROUP.equals(action)) {
            //收到了群解散的消息，取消订阅该群，删除消息记录，刷新群列表
            Log.e("xxx", "xxx==收到群解散的消息");
            HistoryContactManager.deleteHistory(message.sender);
            MessageStore.deleteGroupMsg(message.sender);
            sCallback.onMessageHelperCallback(message.sender, false);
            ContactManager.initData();
        } else if (ChatSysMessageBody.SysMessageType.ACTION_LEAVE_GROUP.equals(action)) {
            //有人退出群
            Log.e("xxx", "xxx==收到有人退群的消息");
            ContactManager.initData();//更新群消息即可
        } else if (ChatSysMessageBody.SysMessageType.ACTION_UPDATE_GROUP.equals(action)) {
            Log.e("xxx", "xxx==收到更新群的消息");
            ContactManager.initData();//更新群消息即可
        } else if (ChatSysMessageBody.SysMessageType.ACTION_WEB_ANNO.equals(action)) {//服务端的发过来的公告信息
            Log.e("xxx", "xxx===========收到公告信息");
            HxAnnoModel annoModel = new HxAnnoModel();
            annoModel.bulletinId = Integer.parseInt(msgBody[1]);
            annoModel.title = msgBody[2];
            annoModel.description = msgBody[3];
            annoModel.creater = msgBody[4];
            annoModel.createDate = Long.parseLong(msgBody[5]);
            annoModel.read = 1;//置公告为未读
            annoModel.recv = UserManager.getClientId();
            LocalAnnoStore.getAnnoStore().store(annoModel);
        } else if (ChatSysMessageBody.SysMessageType.ACTION_WEB_WARN.equals(action)) {//服务端发过来的告警信息
            Log.e("xxx", "xxx===========收到告警信息");
            HxWarnModel warnModel = new HxWarnModel();
            warnModel.id = Integer.parseInt(msgBody[1]);
            warnModel.type = Integer.parseInt(msgBody[2]);
            warnModel.value = msgBody[3];
            warnModel.title = msgBody[4];
            warnModel.stationCode = msgBody[5];
            warnModel.station = msgBody[6];
            warnModel.device = msgBody[7];
            warnModel.time = Long.parseLong(msgBody[8]);
            warnModel.status = Integer.parseInt(msgBody[9]);
            warnModel.read = 1;
            warnModel.recv = UserManager.getClientId();
            LocalWarnStore.getWarnStore().store(warnModel);
        }
    }

    private static OnServiceCallback sCallback;

    public static void setServiceCallback(OnServiceCallback callback) {
        sCallback = callback;
    }

    //用于回调service中的方法
    public interface OnServiceCallback {
        void onMessageHelperCallback(String id, boolean isSubscribe);
    }
}
